<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">









  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



















  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.jpg?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.jpg?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.jpg?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.4.2',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  




  <meta name="description" content="支付流程 商户系统和微信支付系统主要交互说明：  步骤1：用户在商户APP中选择商品，提交订单，选择微信支付。 步骤2：商户后台收到用户支付单，调用微信支付统一下单接口。参见【统一下单API】。 步骤3：统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。参与签名的字段名为appid，partnerid，prepayid，noncestr，timestamp，">
<meta property="og:type" content="article">
<meta property="og:title" content="第三方支付接入-微信支付">
<meta property="og:url" content="https://devzhao.com/post/642277c0.html">
<meta property="og:site_name" content="学而时习之">
<meta property="og:description" content="支付流程 商户系统和微信支付系统主要交互说明：  步骤1：用户在商户APP中选择商品，提交订单，选择微信支付。 步骤2：商户后台收到用户支付单，调用微信支付统一下单接口。参见【统一下单API】。 步骤3：统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。参与签名的字段名为appid，partnerid，prepayid，noncestr，timestamp，">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://qnfile.devzhao.com/blog/2018-10-12-095051.png">
<meta property="og:image" content="https://qnfile.devzhao.com/blog/2018-10-12-095053.png">
<meta property="og:updated_time" content="2018-10-13T13:33:09.951Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="第三方支付接入-微信支付">
<meta name="twitter:description" content="支付流程 商户系统和微信支付系统主要交互说明：  步骤1：用户在商户APP中选择商品，提交订单，选择微信支付。 步骤2：商户后台收到用户支付单，调用微信支付统一下单接口。参见【统一下单API】。 步骤3：统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。参与签名的字段名为appid，partnerid，prepayid，noncestr，timestamp，">
<meta name="twitter:image" content="https://qnfile.devzhao.com/blog/2018-10-12-095051.png">






  <link rel="canonical" href="https://devzhao.com/post/642277c0.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>第三方支付接入-微信支付 | 学而时习之</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b8fcd96e6d9e134b3c9551097ed074a4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div id="showImgFullScrn" style="display: none;"><img id="showImgFullScrnImg" src="" style="max-height:100%"></div>

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">学而时习之</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">时间就是力量</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-shortcut">
    <a href="/shortcut/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-shirtsinbulk"></i> <br />快捷</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://devzhao.com/post/642277c0.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaohan">
      <meta itemprop="description" content="教，是最好的学">
      <meta itemprop="image" content="http://qnfile.devzhao.com/blog/2018-10-12-125720.jpg#/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学而时习之">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">第三方支付接入-微信支付
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2017-09-08 15:53:05" itemprop="dateCreated datePublished" datetime="2017-09-08T15:53:05+08:00">2017-09-08</time>
            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/post/642277c0.html#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论数：</span> <span class="post-comments-count valine-comment-count" data-xid="/post/642277c0.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/post/642277c0.html" class="leancloud_visitors" data-flag-title="第三方支付接入-微信支付">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">31k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <h2 id="支付流程"><a href="#支付流程" class="headerlink" title="支付流程"></a>支付流程</h2><p><img src="https://qnfile.devzhao.com/blog/2018-10-12-095051.png" alt=""></p>
<p>商户系统和微信支付系统主要交互说明：</p>
<ul>
<li>步骤1：用户在商户APP中选择商品，提交订单，选择微信支付。</li>
<li>步骤2：商户后台收到用户支付单，调用微信支付统一下单接口。参见【统一下单API】。</li>
<li>步骤3：统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。参与签名的字段名为appid，partnerid，prepayid，noncestr，timestamp，package。注意：package的值格式为Sign=WXPay</li>
<li>步骤4：商户APP调起微信支付。api参见本章节【app端开发步骤说明】</li>
<li>步骤5：商户后台接收支付通知。api参见【支付结果通知API】</li>
<li>步骤6：商户后台查询支付结果。，api参见【查询订单API】</li>
</ul>
<p><strong>实际开发中简单来说就是以下步骤，一般来说只需要走通前三步即可</strong></p>
<p>后文中的  <em>WEIXINPAY_MCH_ID</em> <em>WEIXINPAY_SIGN_KEY</em>  是在微信商户平台(<a href="https://pay.weixin.qq.com" target="_blank" rel="noopener">https://pay.weixin.qq.com</a>)里面获取， <em>WEIXINPAY_APPID</em> 是appid 在微信开放平台(<a href="https://open.weixin.qq.com/" target="_blank" rel="noopener">https://open.weixin.qq.com/</a>)获取 </p>
<p><em>WXPayUtil</em>在文后附上</p>
<h3 id="1-客户端请求后台接口获取prepayid和签名"><a href="#1-客户端请求后台接口获取prepayid和签名" class="headerlink" title="1.客户端请求后台接口获取prepayid和签名"></a>1.客户端请求后台接口获取prepayid和签名</h3><p><img src="https://qnfile.devzhao.com/blog/2018-10-12-095053.png" alt="http://ojaere508.bkt.clouddn.com/image/pasted/2017-09-13/1505306132179.png"></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line">	/**</span><br><span class="line">	 * App支付接口</span><br><span class="line">	 * @return</span><br><span class="line">	 * @throws Exception</span><br><span class="line">	 */</span><br><span class="line">	@RequestMapping(value=&quot;/weixinpay/pay&quot;,method= RequestMethod.POST)</span><br><span class="line">	public @ResponseBody JSONObject pay(</span><br><span class="line">			@RequestParam(value=&quot;total_amount&quot; ,required =true ) String totalAmount</span><br><span class="line">			) throws Exception&#123;</span><br><span class="line">		JSONObject jsonData = new JSONObject();</span><br><span class="line">		</span><br><span class="line">		//自己系统生成的订单号</span><br><span class="line">		String outTradeNo = String.valueOf(System.currentTimeMillis());</span><br><span class="line">		</span><br><span class="line">		String spbillCreateIp = getRemoteHost();//获取客户端的ip，通过request获取，请自行google具体实现</span><br><span class="line">		String notifyUrl = &quot;https://api.devzhao.com/weixinpay/receive_notify&quot;;</span><br><span class="line">		String tradeType = &quot;APP&quot;;</span><br><span class="line">		String nonceStr = WXPayUtil.getRandomString(32);</span><br><span class="line">		//将要请求微信的参数</span><br><span class="line">		SortedMap&lt;String,Object&gt; weixinOrder = new TreeMap&lt;String,Object&gt;();</span><br><span class="line">		weixinOrder.put(&quot;appid&quot;,WEIXINPAY_APPID);</span><br><span class="line">		weixinOrder.put(&quot;mch_id&quot;,WEIXINPAY_MCH_ID);//微信支付分配的商户号</span><br><span class="line">		weixinOrder.put(&quot;nonce_str&quot;,nonceStr);//随机字符串，不长于32位</span><br><span class="line">		weixinOrder.put(&quot;body&quot;,&quot;我的APP-余额充值&quot;);//商品描述交易字段格式根据不同的应用场景按照以下格式：APP——需传入应用市场上的APP名字-实际商品名称，天天爱消除-游戏充值。</span><br><span class="line">		weixinOrder.put(&quot;out_trade_no&quot;,outTradeNo);//商户系统内部订单号，要求32个字符内，只能是数字、大小写字母_-|*@ ，且在同一个商户号下唯一。详见商户订单号</span><br><span class="line">		java.text.DecimalFormat df=new java.text.DecimalFormat(&quot;0&quot;);  </span><br><span class="line">		weixinOrder.put(&quot;total_fee&quot;, df.format(Integer.parseInt(totalAmount)));//总金额</span><br><span class="line">		weixinOrder.put(&quot;spbill_create_ip&quot;,spbillCreateIp);//用户端实际ip</span><br><span class="line">		weixinOrder.put(&quot;notify_url&quot;,notifyUrl);//接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。</span><br><span class="line">		weixinOrder.put(&quot;trade_type&quot;,tradeType);//支付类型</span><br><span class="line">		</span><br><span class="line">		//计算sign</span><br><span class="line">		String sign = WXPayUtil.createSign(&quot;UTF-8&quot;, weixinOrder,WEIXINPAY_SIGN_KEY);  </span><br><span class="line">		weixinOrder.put(&quot;sign&quot;,sign);//签名</span><br><span class="line">		</span><br><span class="line">		String requestXML = WXPayUtil.getRequestXml(weixinOrder);  </span><br><span class="line">        System.out.println(requestXML);  </span><br><span class="line">        String result = WXPayUtil.httpsRequest(  </span><br><span class="line">                &quot;https://api.mch.weixin.qq.com/pay/unifiedorder&quot;, &quot;POST&quot;,  </span><br><span class="line">                requestXML);  </span><br><span class="line">//        System.out.println(result);  </span><br><span class="line">        Map&lt;String, String&gt; map = null;  </span><br><span class="line">        try &#123;  </span><br><span class="line">            map = WXPayUtil.doXMLParse(result);  </span><br><span class="line">        &#125; catch (JDOMException e) &#123;  </span><br><span class="line">            e.printStackTrace();  </span><br><span class="line">            _log.error(&quot;JDOMException&quot;,e);</span><br><span class="line">            jsonData.put(&quot;success&quot;, 0);</span><br><span class="line">            jsonData.put(&quot;resullt&quot;,null);</span><br><span class="line">        &#125; catch (IOException e) &#123;  </span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            _log.error(&quot;IOException&quot;,e);</span><br><span class="line">            jsonData.put(&quot;success&quot;, 0);</span><br><span class="line">            jsonData.put(&quot;resullt&quot;,null);</span><br><span class="line">        &#125;  </span><br><span class="line">        </span><br><span class="line">        String  prepay_id = map.get(&quot;prepay_id&quot;);</span><br><span class="line">//        二次签名</span><br><span class="line">        SortedMap&lt;String, Object&gt; back = new TreeMap&lt;String, Object&gt;();</span><br><span class="line">        String time = time = Long.toString(new Date(System.currentTimeMillis() / 1000L).getTime());//10位的时间戳</span><br><span class="line">        back.put(&quot;appid&quot;, WEIXINPAY_APPID);</span><br><span class="line">        back.put(&quot;partnerid&quot;, WEIXINPAY_MCH_ID);</span><br><span class="line">        back.put(&quot;prepayid&quot;, prepay_id==null?&quot;&quot;:prepay_id);</span><br><span class="line">        back.put(&quot;package&quot;, &quot;Sign=WXPay&quot;);</span><br><span class="line">        back.put(&quot;noncestr&quot;, nonceStr);</span><br><span class="line">        back.put(&quot;timestamp&quot;, time);</span><br><span class="line">        </span><br><span class="line">        String sign2 = WXPayUtil.createSign(&quot;UTF-8&quot;, back,WEIXINPAY_SIGN_KEY);</span><br><span class="line">        _log.info(&quot;二次签名后返回给前端的签名证书字符串是：&quot; + sign2);</span><br><span class="line"></span><br><span class="line">        JSONObject jsonObject = new JSONObject();</span><br><span class="line">        jsonObject.put(&quot;timeStamp&quot;, time);</span><br><span class="line">        jsonObject.put(&quot;nonceStr&quot;, nonceStr);</span><br><span class="line">        jsonObject.put(&quot;prepay_id&quot;, prepay_id);</span><br><span class="line">        jsonObject.put(&quot;sign&quot;, sign2);</span><br><span class="line"></span><br><span class="line">        _log.info(&quot;二次签名后返回给前端的数据是：&quot; + jsonObject.toJSONString());</span><br><span class="line">        jsonData.put(&quot;resullt&quot;, jsonObject);</span><br><span class="line">        jsonData.put(&quot;success&quot;, 1);</span><br><span class="line">        </span><br><span class="line">		return returnSuccessJson(jsonData);</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure>
<h3 id="2-客户端使用上面获取的值加上其他值向微信服务端发起支付请求"><a href="#2-客户端使用上面获取的值加上其他值向微信服务端发起支付请求" class="headerlink" title="2.客户端使用上面获取的值加上其他值向微信服务端发起支付请求"></a>2.客户端使用上面获取的值加上其他值向微信服务端发起支付请求</h3><p>这里的坑主要是签名，就是第一个步骤里面的“二次签名”部分。</p>
<p>需要注意的：</p>
<ul>
<li>时间戳必须是10位</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">String time = Long.toString(new Date(System.currentTimeMillis() / 1000L).getTime());//10位的时间戳</span><br></pre></td></tr></table></figure>
<ul>
<li>参与签名的参数是以下参数，注意key的大小写要与文档(<a href="https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12&amp;index=2" target="_blank" rel="noopener">https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12&amp;index=2</a>)中保持一致</li>
</ul>
<p>下面是亲测有效的参数</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">back.put(&quot;appid&quot;, WEIXINPAY_APPID);</span><br><span class="line">back.put(&quot;partnerid&quot;, WEIXINPAY_MCH_ID);</span><br><span class="line">back.put(&quot;prepayid&quot;, prepay_id==null?&quot;&quot;:prepay_id);</span><br><span class="line">back.put(&quot;package&quot;, &quot;Sign=WXPay&quot;);</span><br><span class="line">back.put(&quot;noncestr&quot;, nonceStr);</span><br><span class="line">back.put(&quot;timestamp&quot;, time);</span><br></pre></td></tr></table></figure>
<h3 id="3-后台端异步接收微信服务器发过来支付通知"><a href="#3-后台端异步接收微信服务器发过来支付通知" class="headerlink" title="3.后台端异步接收微信服务器发过来支付通知"></a>3.后台端异步接收微信服务器发过来支付通知</h3><p>这里的坑主要是微信发送过来的请求数据的方式是 <strong><em>raw</em></strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 接收异步通知</span><br><span class="line"> * @return</span><br><span class="line"> * @throws Exception</span><br><span class="line"> */</span><br><span class="line">@PublicRequester</span><br><span class="line">@RequestMapping(value=&quot;/weixinpay/receive_notify&quot;,method= RequestMethod.POST)</span><br><span class="line">public void  receiveNotify2() throws Exception&#123;</span><br><span class="line">	</span><br><span class="line">	String line = &quot;&quot;;</span><br><span class="line">       StringBuilder body = new StringBuilder();</span><br><span class="line">       int counter = 0;</span><br><span class="line">       InputStream stream;</span><br><span class="line">       stream = request.getInputStream();</span><br><span class="line">       </span><br><span class="line">       //读取POST提交的数据内容</span><br><span class="line">       BufferedReader reader = new BufferedReader(new InputStreamReader(stream));</span><br><span class="line">       while ((line = reader.readLine()) != null) &#123;</span><br><span class="line">           if(counter &gt; 0)&#123;</span><br><span class="line">               body.append(&quot;\r\n&quot;);</span><br><span class="line">           &#125;</span><br><span class="line">           body.append(line);</span><br><span class="line">           counter++;</span><br><span class="line">       &#125;</span><br><span class="line">       //POST请求的raw数据可以获得</span><br><span class="line">       _log.info(&quot;requestBody:&quot;+body.toString());</span><br><span class="line">	</span><br><span class="line">	Map param = WXPayUtil.xmlToMap(body.toString());</span><br><span class="line">	_log.info(&quot;params:&quot;+param.toString());</span><br><span class="line">	</span><br><span class="line">	String return_code = param.get(&quot;return_code&quot;).toString();</span><br><span class="line">	String result_code = param.get(&quot;result_code&quot;).toString();</span><br><span class="line">	</span><br><span class="line">	String returnStr = &quot;&lt;xml&gt;&lt;return_code&gt;&lt;![CDATA[SUCCESS]]&gt;&lt;/return_code&gt;&lt;return_msg&gt;&lt;![CDATA[OK]]&gt;&lt;/return_msg&gt;&lt;/xml&gt;&quot;;</span><br><span class="line"></span><br><span class="line">	if(return_code.equals(&quot;SUCCESS&quot;) &amp;&amp; result_code.equals(&quot;SUCCESS&quot;))&#123;</span><br><span class="line">		boolean check = WXPayUtil.checkSignature(param,WEIXINPAY_SIGN_KEY);</span><br><span class="line">		_log.info(&quot;params check:&quot;+check);</span><br><span class="line">		//TODO 业务逻辑 。。。。</span><br><span class="line">		</span><br><span class="line">	&#125;else&#123;</span><br><span class="line">		returnStr = &quot;&lt;xml&gt;&lt;return_code&gt;&lt;![CDATA[FAIL]]&gt;&lt;/return_code&gt;&lt;return_msg&gt;&lt;![CDATA[OK]]&gt;&lt;/return_msg&gt;&lt;/xml&gt;&quot;;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	response.setCharacterEncoding(&quot;UTF-8&quot;);  </span><br><span class="line">    response.setContentType(&quot;application/xml; charset=utf-8&quot;);  </span><br><span class="line">    PrintWriter out = null;  </span><br><span class="line">    try &#123;  </span><br><span class="line">        out = response.getWriter();  </span><br><span class="line">        out.append(returnStr);  </span><br><span class="line">        _log.debug(&quot;返回是\n&quot;);  </span><br><span class="line">        _log.debug(returnStr);  </span><br><span class="line">    &#125; catch (IOException e) &#123;  </span><br><span class="line">        e.printStackTrace();  </span><br><span class="line">        _log.error(&quot;&quot;,e);</span><br><span class="line">    &#125; finally &#123;  </span><br><span class="line">        if (out != null) &#123;  </span><br><span class="line">            out.close();  </span><br><span class="line">        &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="4-客户端请求服务器查询支付结果"><a href="#4-客户端请求服务器查询支付结果" class="headerlink" title="4.客户端请求服务器查询支付结果"></a>4.客户端请求服务器查询支付结果</h3><p>这个步骤按照文档<a href="https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_2&amp;index=4" target="_blank" rel="noopener">https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_2&amp;index=4</a>操作即可</p>
<hr>
<p>WXPayUtil</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br><span class="line">381</span><br><span class="line">382</span><br><span class="line">383</span><br><span class="line">384</span><br><span class="line">385</span><br><span class="line">386</span><br><span class="line">387</span><br><span class="line">388</span><br><span class="line">389</span><br><span class="line">390</span><br><span class="line">391</span><br><span class="line">392</span><br><span class="line">393</span><br><span class="line">394</span><br><span class="line">395</span><br><span class="line">396</span><br><span class="line">397</span><br><span class="line">398</span><br><span class="line">399</span><br><span class="line">400</span><br><span class="line">401</span><br><span class="line">402</span><br><span class="line">403</span><br><span class="line">404</span><br><span class="line">405</span><br><span class="line">406</span><br><span class="line">407</span><br><span class="line">408</span><br><span class="line">409</span><br><span class="line">410</span><br><span class="line">411</span><br><span class="line">412</span><br><span class="line">413</span><br><span class="line">414</span><br><span class="line">415</span><br><span class="line">416</span><br><span class="line">417</span><br><span class="line">418</span><br><span class="line">419</span><br><span class="line">420</span><br><span class="line">421</span><br><span class="line">422</span><br><span class="line">423</span><br><span class="line">424</span><br><span class="line">425</span><br><span class="line">426</span><br><span class="line">427</span><br><span class="line">428</span><br><span class="line">429</span><br><span class="line">430</span><br><span class="line">431</span><br><span class="line">432</span><br><span class="line">433</span><br><span class="line">434</span><br><span class="line">435</span><br><span class="line">436</span><br><span class="line">437</span><br><span class="line">438</span><br><span class="line">439</span><br><span class="line">440</span><br><span class="line">441</span><br><span class="line">442</span><br><span class="line">443</span><br><span class="line">444</span><br><span class="line">445</span><br><span class="line">446</span><br><span class="line">447</span><br><span class="line">448</span><br><span class="line">449</span><br><span class="line">450</span><br><span class="line">451</span><br><span class="line">452</span><br><span class="line">453</span><br><span class="line">454</span><br><span class="line">455</span><br><span class="line">456</span><br><span class="line">457</span><br><span class="line">458</span><br><span class="line">459</span><br><span class="line">460</span><br><span class="line">461</span><br><span class="line">462</span><br><span class="line">463</span><br><span class="line">464</span><br><span class="line">465</span><br><span class="line">466</span><br><span class="line">467</span><br><span class="line">468</span><br><span class="line">469</span><br><span class="line">470</span><br><span class="line">471</span><br><span class="line">472</span><br><span class="line">473</span><br><span class="line">474</span><br><span class="line">475</span><br><span class="line">476</span><br><span class="line">477</span><br><span class="line">478</span><br><span class="line">479</span><br><span class="line">480</span><br><span class="line">481</span><br><span class="line">482</span><br><span class="line">483</span><br><span class="line">484</span><br><span class="line">485</span><br><span class="line">486</span><br><span class="line">487</span><br><span class="line">488</span><br><span class="line">489</span><br><span class="line">490</span><br><span class="line">491</span><br><span class="line">492</span><br><span class="line">493</span><br><span class="line">494</span><br><span class="line">495</span><br><span class="line">496</span><br><span class="line">497</span><br><span class="line">498</span><br><span class="line">499</span><br><span class="line">500</span><br><span class="line">501</span><br><span class="line">502</span><br><span class="line">503</span><br><span class="line">504</span><br><span class="line">505</span><br><span class="line">506</span><br><span class="line">507</span><br><span class="line">508</span><br><span class="line">509</span><br><span class="line">510</span><br><span class="line">511</span><br><span class="line">512</span><br><span class="line">513</span><br><span class="line">514</span><br><span class="line">515</span><br><span class="line">516</span><br><span class="line">517</span><br><span class="line">518</span><br><span class="line">519</span><br><span class="line">520</span><br><span class="line">521</span><br><span class="line">522</span><br><span class="line">523</span><br><span class="line">524</span><br><span class="line">525</span><br><span class="line">526</span><br><span class="line">527</span><br><span class="line">528</span><br><span class="line">529</span><br><span class="line">530</span><br><span class="line">531</span><br><span class="line">532</span><br><span class="line">533</span><br><span class="line">534</span><br><span class="line">535</span><br><span class="line">536</span><br><span class="line">537</span><br><span class="line">538</span><br><span class="line">539</span><br><span class="line">540</span><br><span class="line">541</span><br><span class="line">542</span><br><span class="line">543</span><br><span class="line">544</span><br><span class="line">545</span><br><span class="line">546</span><br><span class="line">547</span><br><span class="line">548</span><br><span class="line">549</span><br><span class="line">550</span><br><span class="line">551</span><br><span class="line">552</span><br><span class="line">553</span><br><span class="line">554</span><br><span class="line">555</span><br><span class="line">556</span><br><span class="line">557</span><br><span class="line">558</span><br><span class="line">559</span><br><span class="line">560</span><br><span class="line">561</span><br></pre></td><td class="code"><pre><span class="line">import java.io.BufferedReader;</span><br><span class="line">import java.io.ByteArrayInputStream;</span><br><span class="line">import java.io.File;</span><br><span class="line">import java.io.FileInputStream;</span><br><span class="line">import java.io.IOException;</span><br><span class="line">import java.io.InputStream;</span><br><span class="line">import java.io.InputStreamReader;</span><br><span class="line">import java.io.OutputStream;</span><br><span class="line">import java.io.StringWriter;</span><br><span class="line">import java.net.ConnectException;</span><br><span class="line">import java.net.HttpURLConnection;</span><br><span class="line">import java.net.URL;</span><br><span class="line">import java.security.KeyStore;</span><br><span class="line">import java.security.MessageDigest;</span><br><span class="line">import java.util.Arrays;</span><br><span class="line">import java.util.HashMap;</span><br><span class="line">import java.util.Iterator;</span><br><span class="line">import java.util.List;</span><br><span class="line">import java.util.Map;</span><br><span class="line">import java.util.Random;</span><br><span class="line">import java.util.Set;</span><br><span class="line">import java.util.SortedMap;</span><br><span class="line">import java.util.UUID;</span><br><span class="line"></span><br><span class="line">import javax.crypto.Mac;</span><br><span class="line">import javax.crypto.spec.SecretKeySpec;</span><br><span class="line">import javax.net.ssl.SSLContext;</span><br><span class="line">import javax.xml.parsers.DocumentBuilder;</span><br><span class="line">import javax.xml.parsers.DocumentBuilderFactory;</span><br><span class="line">import javax.xml.transform.OutputKeys;</span><br><span class="line">import javax.xml.transform.Transformer;</span><br><span class="line">import javax.xml.transform.TransformerFactory;</span><br><span class="line">import javax.xml.transform.dom.DOMSource;</span><br><span class="line">import javax.xml.transform.stream.StreamResult;</span><br><span class="line"></span><br><span class="line">import org.apache.http.Consts;</span><br><span class="line">import org.apache.http.HttpEntity;</span><br><span class="line">import org.apache.http.client.methods.CloseableHttpResponse;</span><br><span class="line">import org.apache.http.client.methods.HttpPost;</span><br><span class="line">import org.apache.http.conn.ssl.SSLConnectionSocketFactory;</span><br><span class="line">import org.apache.http.entity.StringEntity;</span><br><span class="line">import org.apache.http.impl.client.CloseableHttpClient;</span><br><span class="line">import org.apache.http.impl.client.HttpClients;</span><br><span class="line">import org.apache.http.ssl.SSLContexts;</span><br><span class="line">import org.apache.http.util.EntityUtils;</span><br><span class="line">import org.jdom.Document;</span><br><span class="line">import org.jdom.Element;</span><br><span class="line">import org.jdom.JDOMException;</span><br><span class="line">import org.jdom.input.SAXBuilder;</span><br><span class="line">import org.slf4j.Logger;</span><br><span class="line">import org.slf4j.LoggerFactory;</span><br><span class="line">import org.w3c.dom.Node;</span><br><span class="line">import org.w3c.dom.NodeList;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">public class WXPayUtil &#123;</span><br><span class="line">	private final static String FIELD_SIGN = &quot;sign&quot;;</span><br><span class="line">	</span><br><span class="line">	//随机字符串生成  </span><br><span class="line">    public static String getRandomString(int length) &#123; //length表示生成字符串的长度      </span><br><span class="line">           String base = &quot;abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;         </span><br><span class="line">           Random random = new Random();         </span><br><span class="line">           StringBuffer sb = new StringBuffer();         </span><br><span class="line">           for (int i = 0; i &lt; length; i++) &#123;         </span><br><span class="line">               int number = random.nextInt(base.length());         </span><br><span class="line">               sb.append(base.charAt(number));         </span><br><span class="line">           &#125;         </span><br><span class="line">           return sb.toString();         </span><br><span class="line">        &#125;    </span><br><span class="line">    //请求xml组装  </span><br><span class="line">      public static String getRequestXml(SortedMap&lt;String,Object&gt; parameters)&#123;  </span><br><span class="line">            StringBuffer sb = new StringBuffer();  </span><br><span class="line">            sb.append(&quot;&lt;xml&gt;&quot;);  </span><br><span class="line">            Set es = parameters.entrySet();  </span><br><span class="line">            Iterator it = es.iterator();  </span><br><span class="line">            while(it.hasNext()) &#123;  </span><br><span class="line">                Map.Entry entry = (Map.Entry)it.next();  </span><br><span class="line">                String key = (String)entry.getKey();  </span><br><span class="line">                String value = (String)entry.getValue();  </span><br><span class="line">                if (&quot;attach&quot;.equalsIgnoreCase(key)||&quot;body&quot;.equalsIgnoreCase(key)||&quot;sign&quot;.equalsIgnoreCase(key)) &#123;  </span><br><span class="line">                    sb.append(&quot;&lt;&quot;+key+&quot;&gt;&quot;+&quot;&lt;![CDATA[&quot;+value+&quot;]]&gt;&lt;/&quot;+key+&quot;&gt;&quot;);  </span><br><span class="line">                &#125;else &#123;  </span><br><span class="line">                    sb.append(&quot;&lt;&quot;+key+&quot;&gt;&quot;+value+&quot;&lt;/&quot;+key+&quot;&gt;&quot;);  </span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;  </span><br><span class="line">            sb.append(&quot;&lt;/xml&gt;&quot;);  </span><br><span class="line">            return sb.toString();  </span><br><span class="line">        &#125;  </span><br><span class="line">      //生成签名  </span><br><span class="line">      public static String createSign(String characterEncoding,SortedMap&lt;String,Object&gt; parameters,String API_KEY) throws Exception&#123;  </span><br><span class="line">            StringBuffer sb = new StringBuffer();  </span><br><span class="line">            Set es = parameters.entrySet();  </span><br><span class="line">            Iterator it = es.iterator();  </span><br><span class="line">            while(it.hasNext()) &#123;  </span><br><span class="line">                Map.Entry entry = (Map.Entry)it.next();  </span><br><span class="line">                String k = (String)entry.getKey();  </span><br><span class="line">                Object v = entry.getValue();  </span><br><span class="line">                if(null != v &amp;&amp; !&quot;&quot;.equals(v)  </span><br><span class="line">                        &amp;&amp; !&quot;sign&quot;.equals(k) &amp;&amp; !&quot;key&quot;.equals(k)) &#123;  </span><br><span class="line">                    sb.append(k + &quot;=&quot; + v + &quot;&amp;&quot;);  </span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;  </span><br><span class="line">            sb.append(&quot;key=&quot; + API_KEY);</span><br><span class="line">            System.out.println(sb);</span><br><span class="line">            String sign = MD5(sb.toString()).toUpperCase();  </span><br><span class="line">            return sign;  </span><br><span class="line">        &#125;  </span><br><span class="line">      //请求方法  </span><br><span class="line">      public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) &#123;  </span><br><span class="line">            try &#123;  </span><br><span class="line">                 </span><br><span class="line">                URL url = new URL(requestUrl);  </span><br><span class="line">                HttpURLConnection conn = (HttpURLConnection) url.openConnection();  </span><br><span class="line">                </span><br><span class="line">                conn.setDoOutput(true);  </span><br><span class="line">                conn.setDoInput(true);  </span><br><span class="line">                conn.setUseCaches(false);  </span><br><span class="line">                // 设置请求方式（GET/POST）  </span><br><span class="line">                conn.setRequestMethod(requestMethod);  </span><br><span class="line">                conn.setRequestProperty(&quot;content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);  </span><br><span class="line">                // 当outputStr不为null时向输出流写数据  </span><br><span class="line">                if (null != outputStr) &#123;  </span><br><span class="line">                    OutputStream outputStream = conn.getOutputStream();  </span><br><span class="line">                    // 注意编码格式  </span><br><span class="line">                    outputStream.write(outputStr.getBytes(&quot;UTF-8&quot;));  </span><br><span class="line">                    outputStream.close();  </span><br><span class="line">                &#125;  </span><br><span class="line">                // 从输入流读取返回内容  </span><br><span class="line">                InputStream inputStream = conn.getInputStream();  </span><br><span class="line">                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, &quot;utf-8&quot;);  </span><br><span class="line">                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  </span><br><span class="line">                String str = null;  </span><br><span class="line">                StringBuffer buffer = new StringBuffer();  </span><br><span class="line">                while ((str = bufferedReader.readLine()) != null) &#123;  </span><br><span class="line">                    buffer.append(str);  </span><br><span class="line">                &#125;  </span><br><span class="line">                // 释放资源  </span><br><span class="line">                bufferedReader.close();  </span><br><span class="line">                inputStreamReader.close();  </span><br><span class="line">                inputStream.close();  </span><br><span class="line">                inputStream = null;  </span><br><span class="line">                conn.disconnect();  </span><br><span class="line">                return buffer.toString();  </span><br><span class="line">            &#125; catch (ConnectException ce) &#123;  </span><br><span class="line">                System.out.println(&quot;连接超时：&#123;&#125;&quot;+ ce);  </span><br><span class="line">            &#125; catch (Exception e) &#123;  </span><br><span class="line">                System.out.println(&quot;https请求异常：&#123;&#125;&quot;+ e);  </span><br><span class="line">            &#125;  </span><br><span class="line">            return null;  </span><br><span class="line">        &#125;  </span><br><span class="line">      //退款的请求方法  </span><br><span class="line">      public static String httpsRequest2(String requestUrl, String requestMethod, String outputStr) throws Exception &#123;  </span><br><span class="line">            KeyStore keyStore  = KeyStore.getInstance(&quot;PKCS12&quot;);  </span><br><span class="line">            StringBuilder res = new StringBuilder(&quot;&quot;);  </span><br><span class="line">            FileInputStream instream = new FileInputStream(new File(&quot;/home/apiclient_cert.p12&quot;));  </span><br><span class="line">            try &#123;  </span><br><span class="line">                keyStore.load(instream, &quot;&quot;.toCharArray());  </span><br><span class="line">            &#125; finally &#123;  </span><br><span class="line">                instream.close();  </span><br><span class="line">            &#125;  </span><br><span class="line">  </span><br><span class="line">            // Trust own CA and all self-signed certs  </span><br><span class="line">            SSLContext sslcontext = SSLContexts.custom()  </span><br><span class="line">                    .loadKeyMaterial(keyStore, &quot;1313329201&quot;.toCharArray())  </span><br><span class="line">                    .build();  </span><br><span class="line">            // Allow TLSv1 protocol only  </span><br><span class="line">            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  </span><br><span class="line">                    sslcontext,  </span><br><span class="line">                    new String[] &#123; &quot;TLSv1&quot; &#125;,  </span><br><span class="line">                    null,  </span><br><span class="line">                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);  </span><br><span class="line">            CloseableHttpClient httpclient = HttpClients.custom()  </span><br><span class="line">                    .setSSLSocketFactory(sslsf)  </span><br><span class="line">                    .build();  </span><br><span class="line">            try &#123;  </span><br><span class="line">  </span><br><span class="line">                HttpPost httpost = new HttpPost(&quot;https://api.mch.weixin.qq.com/secapi/pay/refund&quot;);  </span><br><span class="line">                httpost.addHeader(&quot;Connection&quot;, &quot;keep-alive&quot;);  </span><br><span class="line">                httpost.addHeader(&quot;Accept&quot;, &quot;*/*&quot;);  </span><br><span class="line">                httpost.addHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded; charset=UTF-8&quot;);  </span><br><span class="line">                httpost.addHeader(&quot;Host&quot;, &quot;api.mch.weixin.qq.com&quot;);  </span><br><span class="line">                httpost.addHeader(&quot;X-Requested-With&quot;, &quot;XMLHttpRequest&quot;);  </span><br><span class="line">                httpost.addHeader(&quot;Cache-Control&quot;, &quot;max-age=0&quot;);  </span><br><span class="line">                httpost.addHeader(&quot;User-Agent&quot;, &quot;Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) &quot;);  </span><br><span class="line">                 StringEntity entity2 = new StringEntity(outputStr ,Consts.UTF_8);  </span><br><span class="line">                 httpost.setEntity(entity2);  </span><br><span class="line">                System.out.println(&quot;executing request&quot; + httpost.getRequestLine());  </span><br><span class="line">  </span><br><span class="line">                CloseableHttpResponse response = httpclient.execute(httpost);  </span><br><span class="line">                 </span><br><span class="line">                try &#123;  </span><br><span class="line">                    HttpEntity entity = response.getEntity();  </span><br><span class="line">                      </span><br><span class="line">                    System.out.println(&quot;----------------------------------------&quot;);  </span><br><span class="line">                    System.out.println(response.getStatusLine());  </span><br><span class="line">                    if (entity != null) &#123;  </span><br><span class="line">                        System.out.println(&quot;Response content length: &quot; + entity.getContentLength());  </span><br><span class="line">                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));  </span><br><span class="line">                        String text;  </span><br><span class="line">                        while ((text = bufferedReader.readLine()) != null) &#123;  </span><br><span class="line">                            res.append(text);  </span><br><span class="line">                            System.out.println(text);  </span><br><span class="line">                        &#125;  </span><br><span class="line">                         </span><br><span class="line">                    &#125;  </span><br><span class="line">                    EntityUtils.consume(entity);  </span><br><span class="line">                &#125; finally &#123;  </span><br><span class="line">                    response.close();  </span><br><span class="line">                &#125;  </span><br><span class="line">            &#125; finally &#123;  </span><br><span class="line">                httpclient.close();  </span><br><span class="line">            &#125;  </span><br><span class="line">            return  res.toString();  </span><br><span class="line">              </span><br><span class="line">        &#125;  </span><br><span class="line">      //xml解析  </span><br><span class="line">      public static Map doXMLParse(String strxml) throws JDOMException, IOException &#123;  </span><br><span class="line">            strxml = strxml.replaceFirst(&quot;encoding=\&quot;.*\&quot;&quot;, &quot;encoding=\&quot;UTF-8\&quot;&quot;);  </span><br><span class="line">  </span><br><span class="line">            if(null == strxml || &quot;&quot;.equals(strxml)) &#123;  </span><br><span class="line">                return null;  </span><br><span class="line">            &#125;  </span><br><span class="line">              </span><br><span class="line">            Map m = new HashMap();  </span><br><span class="line">              </span><br><span class="line">            InputStream in = new ByteArrayInputStream(strxml.getBytes(&quot;UTF-8&quot;));  </span><br><span class="line">            SAXBuilder builder = new SAXBuilder();  </span><br><span class="line">            Document doc = builder.build(in);  </span><br><span class="line">            Element root = doc.getRootElement();  </span><br><span class="line">            List list = root.getChildren();  </span><br><span class="line">            Iterator it = list.iterator();  </span><br><span class="line">            while(it.hasNext()) &#123;  </span><br><span class="line">                Element e = (Element) it.next();  </span><br><span class="line">                String k = e.getName();  </span><br><span class="line">                String v = &quot;&quot;;  </span><br><span class="line">                List children = e.getChildren();  </span><br><span class="line">                if(children.isEmpty()) &#123;  </span><br><span class="line">                    v = e.getTextNormalize();  </span><br><span class="line">                &#125; else &#123;  </span><br><span class="line">                    v = getChildrenText(children);  </span><br><span class="line">                &#125;  </span><br><span class="line">                  </span><br><span class="line">                m.put(k, v);  </span><br><span class="line">            &#125;  </span><br><span class="line">              </span><br><span class="line">            //关闭流  </span><br><span class="line">            in.close();  </span><br><span class="line">              </span><br><span class="line">            return m;  </span><br><span class="line">        &#125;  </span><br><span class="line">        </span><br><span class="line">      public static String getChildrenText(List children) &#123;  </span><br><span class="line">            StringBuffer sb = new StringBuffer();  </span><br><span class="line">            if(!children.isEmpty()) &#123;  </span><br><span class="line">                Iterator it = children.iterator();  </span><br><span class="line">                while(it.hasNext()) &#123;  </span><br><span class="line">                    Element e = (Element) it.next();  </span><br><span class="line">                    String name = e.getName();  </span><br><span class="line">                    String value = e.getTextNormalize();  </span><br><span class="line">                    List list = e.getChildren();  </span><br><span class="line">                    sb.append(&quot;&lt;&quot; + name + &quot;&gt;&quot;);  </span><br><span class="line">                    if(!list.isEmpty()) &#123;  </span><br><span class="line">                        sb.append(getChildrenText(list));  </span><br><span class="line">                    &#125;  </span><br><span class="line">                    sb.append(value);  </span><br><span class="line">                    sb.append(&quot;&lt;/&quot; + name + &quot;&gt;&quot;);  </span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;  </span><br><span class="line">              </span><br><span class="line">            return sb.toString();  </span><br><span class="line">        &#125; </span><br><span class="line">    /**</span><br><span class="line">     * XML格式字符串转换为Map</span><br><span class="line">     *</span><br><span class="line">     * @param strXML XML字符串</span><br><span class="line">     * @return XML数据转换后的Map</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    public static Map&lt;String, String&gt; xmlToMap(String strXML) throws Exception &#123;</span><br><span class="line">        try &#123;</span><br><span class="line">            Map&lt;String, String&gt; data = new HashMap&lt;String, String&gt;();</span><br><span class="line">            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();</span><br><span class="line">            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();</span><br><span class="line">            InputStream stream = new ByteArrayInputStream(strXML.getBytes(&quot;UTF-8&quot;));</span><br><span class="line">            org.w3c.dom.Document doc = documentBuilder.parse(stream);</span><br><span class="line">            doc.getDocumentElement().normalize();</span><br><span class="line">            NodeList nodeList = doc.getDocumentElement().getChildNodes();</span><br><span class="line">            for (int idx = 0; idx &lt; nodeList.getLength(); ++idx) &#123;</span><br><span class="line">                Node node = nodeList.item(idx);</span><br><span class="line">                if (node.getNodeType() == Node.ELEMENT_NODE) &#123;</span><br><span class="line">                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;</span><br><span class="line">                    data.put(element.getNodeName(), element.getTextContent());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            try &#123;</span><br><span class="line">                stream.close();</span><br><span class="line">            &#125; catch (Exception ex) &#123;</span><br><span class="line">                // do nothing</span><br><span class="line">            &#125;</span><br><span class="line">            return data;</span><br><span class="line">        &#125; catch (Exception ex) &#123;</span><br><span class="line">            WXPayUtil.getLogger().warn(&quot;Invalid XML, can not convert to map. Error message: &#123;&#125;. XML content: &#123;&#125;&quot;, ex.getMessage(), strXML);</span><br><span class="line">            throw ex;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 将Map转换为XML格式的字符串</span><br><span class="line">     *</span><br><span class="line">     * @param data Map类型数据</span><br><span class="line">     * @return XML格式的字符串</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    public static String mapToXml(Map&lt;String, String&gt; data) throws Exception &#123;</span><br><span class="line">        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();</span><br><span class="line">        DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();</span><br><span class="line">        org.w3c.dom.Document document = documentBuilder.newDocument();</span><br><span class="line">        org.w3c.dom.Element root = document.createElement(&quot;xml&quot;);</span><br><span class="line">        document.appendChild(root);</span><br><span class="line">        for (String key: data.keySet()) &#123;</span><br><span class="line">            String value = data.get(key);</span><br><span class="line">            if (value == null) &#123;</span><br><span class="line">                value = &quot;&quot;;</span><br><span class="line">            &#125;</span><br><span class="line">            value = value.trim();</span><br><span class="line">            org.w3c.dom.Element filed = document.createElement(key);</span><br><span class="line">            filed.appendChild(document.createTextNode(value));</span><br><span class="line">            root.appendChild(filed);</span><br><span class="line">        &#125;</span><br><span class="line">        TransformerFactory tf = TransformerFactory.newInstance();</span><br><span class="line">        Transformer transformer = tf.newTransformer();</span><br><span class="line">        DOMSource source = new DOMSource(document);</span><br><span class="line">        transformer.setOutputProperty(OutputKeys.ENCODING, &quot;UTF-8&quot;);</span><br><span class="line">        transformer.setOutputProperty(OutputKeys.INDENT, &quot;yes&quot;);</span><br><span class="line">        StringWriter writer = new StringWriter();</span><br><span class="line">        StreamResult result = new StreamResult(writer);</span><br><span class="line">        transformer.transform(source, result);</span><br><span class="line">        String output = writer.getBuffer().toString(); //.replaceAll(&quot;\n|\r&quot;, &quot;&quot;);</span><br><span class="line">        try &#123;</span><br><span class="line">            writer.close();</span><br><span class="line">        &#125;</span><br><span class="line">        catch (Exception ex) &#123;</span><br><span class="line">        &#125;</span><br><span class="line">        return output;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成带有 sign 的 XML 格式字符串</span><br><span class="line">     *</span><br><span class="line">     * @param data Map类型数据</span><br><span class="line">     * @param key API密钥</span><br><span class="line">     * @return 含有sign字段的XML</span><br><span class="line">     */</span><br><span class="line">    public static String generateSignedXml(final Map&lt;String, String&gt; data, String key) throws Exception &#123;</span><br><span class="line">        return generateSignedXml(data, key, SignType.MD5);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成带有 sign 的 XML 格式字符串</span><br><span class="line">     *</span><br><span class="line">     * @param data Map类型数据</span><br><span class="line">     * @param key API密钥</span><br><span class="line">     * @param signType 签名类型</span><br><span class="line">     * @return 含有sign字段的XML</span><br><span class="line">     */</span><br><span class="line">    public static String generateSignedXml(final Map&lt;String, String&gt; data, String key, String signType) throws Exception &#123;</span><br><span class="line">        String sign = generateSignature(data, key, signType);</span><br><span class="line">        data.put(FIELD_SIGN, sign);</span><br><span class="line">        return mapToXml(data);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断签名是否正确</span><br><span class="line">     *</span><br><span class="line">     * @param xmlStr XML格式数据</span><br><span class="line">     * @param key API密钥</span><br><span class="line">     * @return 签名是否正确</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    public static boolean isSignatureValid(String xmlStr, String key) throws Exception &#123;</span><br><span class="line">        Map&lt;String, String&gt; data = xmlToMap(xmlStr);</span><br><span class="line">        if (!data.containsKey(FIELD_SIGN) ) &#123;</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line">        String sign = data.get(FIELD_SIGN);</span><br><span class="line">        return generateSignature(data, key).equals(sign);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断签名是否正确，必须包含sign字段，否则返回false。使用MD5签名。</span><br><span class="line">     *</span><br><span class="line">     * @param data Map类型数据</span><br><span class="line">     * @param key API密钥</span><br><span class="line">     * @return 签名是否正确</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    public static boolean isSignatureValid(Map&lt;String, String&gt; data, String key) throws Exception &#123;</span><br><span class="line">        return isSignatureValid(data, key, SignType.MD5);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 判断签名是否正确，必须包含sign字段，否则返回false。</span><br><span class="line">     *</span><br><span class="line">     * @param data Map类型数据</span><br><span class="line">     * @param key API密钥</span><br><span class="line">     * @param signType 签名方式</span><br><span class="line">     * @return 签名是否正确</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    public static boolean isSignatureValid(Map&lt;String, String&gt; data, String key, String signType) throws Exception &#123;</span><br><span class="line">        if (!data.containsKey(FIELD_SIGN) ) &#123;</span><br><span class="line">            return false;</span><br><span class="line">        &#125;</span><br><span class="line">        String sign = data.get(FIELD_SIGN);</span><br><span class="line">        return generateSignature(data, key, signType).equals(sign);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成签名</span><br><span class="line">     *</span><br><span class="line">     * @param data 待签名数据</span><br><span class="line">     * @param key API密钥</span><br><span class="line">     * @return 签名</span><br><span class="line">     */</span><br><span class="line">    public static String generateSignature(final Map&lt;String, String&gt; data, String key) throws Exception &#123;</span><br><span class="line">        return generateSignature(data, key, SignType.MD5);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。</span><br><span class="line">     *</span><br><span class="line">     * @param data 待签名数据</span><br><span class="line">     * @param key API密钥</span><br><span class="line">     * @param signType 签名方式</span><br><span class="line">     * @return 签名</span><br><span class="line">     */</span><br><span class="line">    public static String generateSignature(final Map&lt;String, String&gt; data, String key, String signType) throws Exception &#123;</span><br><span class="line">        Set&lt;String&gt; keySet = data.keySet();</span><br><span class="line">        String[] keyArray = keySet.toArray(new String[keySet.size()]);</span><br><span class="line">        Arrays.sort(keyArray);</span><br><span class="line">        StringBuilder sb = new StringBuilder();</span><br><span class="line">        for (String k : keyArray) &#123;</span><br><span class="line">            if (k.equals(FIELD_SIGN)) &#123;</span><br><span class="line">                continue;</span><br><span class="line">            &#125;</span><br><span class="line">            if (data.get(k).trim().length() &gt; 0) // 参数值为空，则不参与签名</span><br><span class="line">                sb.append(k).append(&quot;=&quot;).append(data.get(k).trim()).append(&quot;&amp;&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        sb.append(&quot;key=&quot;).append(key);</span><br><span class="line">        if (SignType.MD5.equals(signType)) &#123;</span><br><span class="line">            return MD5(sb.toString()).toUpperCase();</span><br><span class="line">        &#125;</span><br><span class="line">        else if (SignType.HMACSHA256.equals(signType)) &#123;</span><br><span class="line">            return HMACSHA256(sb.toString(), key);</span><br><span class="line">        &#125;</span><br><span class="line">        else &#123;</span><br><span class="line">            throw new Exception(String.format(&quot;Invalid sign_type: %s&quot;, signType));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取随机字符串 Nonce Str</span><br><span class="line">     *</span><br><span class="line">     * @return String 随机字符串</span><br><span class="line">     */</span><br><span class="line">    public static String generateNonceStr() &#123;</span><br><span class="line">        return UUID.randomUUID().toString().replaceAll(&quot;-&quot;, &quot;&quot;).substring(0, 32);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成 MD5</span><br><span class="line">     *</span><br><span class="line">     * @param data 待处理数据</span><br><span class="line">     * @return MD5结果</span><br><span class="line">     */</span><br><span class="line">    public static String MD5(String data) throws Exception &#123;</span><br><span class="line">        java.security.MessageDigest md = MessageDigest.getInstance(&quot;MD5&quot;);</span><br><span class="line">        byte[] array = md.digest(data.getBytes(&quot;UTF-8&quot;));</span><br><span class="line">        StringBuilder sb = new StringBuilder();</span><br><span class="line">        for (byte item : array) &#123;</span><br><span class="line">            sb.append(Integer.toHexString((item &amp; 0xFF) | 0x100).substring(1, 3));</span><br><span class="line">        &#125;</span><br><span class="line">        return sb.toString().toUpperCase();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成 HMACSHA256</span><br><span class="line">     * @param data 待处理数据</span><br><span class="line">     * @param key 密钥</span><br><span class="line">     * @return 加密结果</span><br><span class="line">     * @throws Exception</span><br><span class="line">     */</span><br><span class="line">    public static String HMACSHA256(String data, String key) throws Exception &#123;</span><br><span class="line">        Mac sha256_HMAC = Mac.getInstance(&quot;HmacSHA256&quot;);</span><br><span class="line">        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(&quot;UTF-8&quot;), &quot;HmacSHA256&quot;);</span><br><span class="line">        sha256_HMAC.init(secret_key);</span><br><span class="line">        byte[] array = sha256_HMAC.doFinal(data.getBytes(&quot;UTF-8&quot;));</span><br><span class="line">        StringBuilder sb = new StringBuilder();</span><br><span class="line">        for (byte item : array) &#123;</span><br><span class="line">            sb.append(Integer.toHexString((item &amp; 0xFF) | 0x100).substring(1, 3));</span><br><span class="line">        &#125;</span><br><span class="line">        return sb.toString().toUpperCase();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 日志</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    public static Logger getLogger() &#123;</span><br><span class="line">        Logger logger = LoggerFactory.getLogger(&quot;wxpay java sdk&quot;);</span><br><span class="line">        return logger;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取当前时间戳，单位秒</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    public static long getCurrentTimestamp() &#123;</span><br><span class="line">        return System.currentTimeMillis()/1000;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 获取当前时间戳，单位毫秒</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    public static long getCurrentTimestampMs() &#123;</span><br><span class="line">        return System.currentTimeMillis();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 生成 uuid， 即用来标识一笔单，也用做 nonce_str</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    public static String generateUUID() &#123;</span><br><span class="line">        return UUID.randomUUID().toString().replaceAll(&quot;-&quot;, &quot;&quot;).substring(0, 32);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    /** </span><br><span class="line">     * 验证签名 </span><br><span class="line">     * </span><br><span class="line">     * @param token 微信服务器token，在env.properties文件中配置的和在开发者中心配置的必须一致 </span><br><span class="line">     * @param signature 微信服务器传过来sha1加密的证书签名</span><br><span class="line">     * @param timestamp 时间戳</span><br><span class="line">     * @param nonce 随机数 </span><br><span class="line">     * @return </span><br><span class="line">     * @throws Exception </span><br><span class="line">     */  </span><br><span class="line">    public static boolean checkSignature(Map&lt;String, String&gt; data, String key) throws Exception &#123;  </span><br><span class="line">    	</span><br><span class="line">    	String genSign = generateSignature(data, key);</span><br><span class="line">    	String sign = data.get(&quot;sign&quot;);</span><br><span class="line">    	return genSign.equals(sign);</span><br><span class="line">    &#125;  </span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持分享输出，感谢你的支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="zhaohan 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="zhaohan 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>zhaohan</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://devzhao.com/post/642277c0.html" title="第三方支付接入-微信支付">https://devzhao.com/post/642277c0.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/post/1de7d001.html" rel="next" title="第三方支付接入-支付宝">
                <i class="fa fa-chevron-left"></i> 第三方支付接入-支付宝
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/post/67c3675.html" rel="prev" title="网页端调用APP">
                网页端调用APP <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://qnfile.devzhao.com/blog/2018-10-12-125720.jpg#/images/avatar.gif"
                alt="zhaohan" />
            
              <p class="site-author-name" itemprop="name">zhaohan</p>
              <p class="site-description motion-element" itemprop="description">教，是最好的学</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">148</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">33</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">29</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#支付流程"><span class="nav-number">1.</span> <span class="nav-text">支付流程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-客户端请求后台接口获取prepayid和签名"><span class="nav-number">1.1.</span> <span class="nav-text">1.客户端请求后台接口获取prepayid和签名</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-客户端使用上面获取的值加上其他值向微信服务端发起支付请求"><span class="nav-number">1.2.</span> <span class="nav-text">2.客户端使用上面获取的值加上其他值向微信服务端发起支付请求</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-后台端异步接收微信服务器发过来支付通知"><span class="nav-number">1.3.</span> <span class="nav-text">3.后台端异步接收微信服务器发过来支付通知</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-客户端请求服务器查询支付结果"><span class="nav-number">1.4.</span> <span class="nav-text">4.客户端请求服务器查询支付结果</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaohan</span>

  

  
</div>


  










        
<div class="busuanzi-count">
  <!--<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>-->

  <script async src="//cdn.busuanzi.ibruce.info/cdn/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <!-- <i class="fa fa-user-circle"></i> -->
      <i>已有</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      <i>位访客浏览过此网站</i>
    </span>
  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz',
        appKey: 'N7MTJbRdufk8MAg3yeK6Gs9U',
        placeholder: '说点什么吧...',
        avatar:'mm',
        meta:guest,
        pageSize:'10' || 10,
        visitor: false
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(counter.time + 1);
            })
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1}))
                .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function () {
                  console.log('Failed to create');
                });
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz",
                'X-LC-Key': "N7MTJbRdufk8MAg3yeK6Gs9U",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  
  

  

  

  

  

  

</body>
</html>
